from abc import ABCMeta, abstractmethod
from sqlalchemy.orm import Session
from docker import DockerClient
from app.controller.model.compute import GetComputeListRes, GetComputeListItem
from app.dao.compute import get_compute, get_compute_count
from app.docker import Client


class ComputeLister(metaclass=ABCMeta):
    @abstractmethod
    def list(self) -> GetComputeListRes:
        pass


class ComputeListerImpl(ComputeLister):
    db: Session
    page: int
    size: int
    client: DockerClient

    def __init__(self, db: Session, *, page: int, size: int, client: DockerClient) -> None:
        super().__init__()
        self.db = db
        self.page = page
        self.size = size
        self.client = client

    def _get_service_form_db(self):
        return get_compute(self.db)

    def _get_service_num_form_db(self):
        return get_compute_count(self.db)

    def list(self) -> GetComputeListRes:
        computes = self._get_service_form_db()
        count = self._get_service_num_form_db()

        items = []
        for compute in computes:
            items.append(GetComputeListItem(id=compute.service_id, mainNode=compute.mainnode, size=compute.size,
                         mainMemory=compute.main_memory, slaveMemory=compute.slave_memory, type=compute.type, time=compute.time))

        return GetComputeListRes(total=count, item=items)


def get_compute_lister(db: Session, *, page: int, size: int) -> ComputeLister:
    return ComputeListerImpl(db, page=page, size=size, client=Client().client)
